package com.mamingchao.concurrent.cas;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Created by mamingchao on 2020/7/7.
 */
public class PhaserTest {

    static MyPhaser phaser = new MyPhaser();

    /**
     * 定义人
     */
    static class Person extends Thread {

        private String name;

        Person(String name) {
            this.name = name;
        }


        private void arrive() {
            this.sleepAWhile();
            System.out.printf("%s 已经到了", name);
            System.out.println();
            phaser.arriveAndAwaitAdvance();

        }

        private void eat() {
            this.sleepAWhile();
            System.out.printf("%s 吃饭了", name);
            System.out.println();
            phaser.arriveAndAwaitAdvance();
        }

        private void leave() {
            this.sleepAWhile();
            System.out.printf("%s 离场了", name);
            System.out.println();
            phaser.arriveAndAwaitAdvance();
        }

        private void hug() {

            if ("新郎".equals(name) || "新娘".equals(name)) {
                this.sleepAWhile();
                System.out.printf("%s 进入洞房", name);
                System.out.println();
                phaser.arriveAndAwaitAdvance();
            } else {
                phaser.arriveAndDeregister();
            }
        }

        private void sleepAWhile() {
            int seconds = new Random().nextInt(10);
            try{
                TimeUnit.SECONDS.sleep(seconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void run() {
            this.arrive();
            this.eat();
            this.leave();
            this.hug();
        }
    }

    static class MyPhaser extends Phaser{

        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.printf("%d个人 所有人都到齐了", registeredParties);
                    System.out.println();
                    return false;
                case 1:
                    System.out.printf("%d个人 所有人都吃完了", registeredParties);
                    System.out.println();
                    return false;
                case 2:
                    System.out.printf("%d个人 都离开了", registeredParties);
                    System.out.println();
                    return false;
                case 3:
                    System.out.println("新郎新娘入洞房");
                    return true;
                default:
                    return true;
            }
        }
    }


    public static void main(String[] args) {
        phaser.bulkRegister(7);

        for (int i=0;i<5;i++) {
            new Thread(new Person("宾客-" + i)).start();
        }

        new Thread(new Person("新娘")).start();
        new Thread(new Person("新郎")).start();

    }

}
